package cn.brilliantfuture.commentry.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;

import javax.naming.NamingException;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.jboss.resteasy.annotations.providers.jaxb.json.BadgerFish;

import cn.brilliantfuture.commentry.exception.ParamErrorException;
import cn.brilliantfuture.commentry.util.DateTimeHelper;
import cn.brilliantfuture.commentry.util.JDBCDataSource;

/**
 * 
 * Title: Communication Entry
 * 
 * Author:  LiTian  
 *
 * Date: 2013-1-18
 * 
 * Description: 通用接口2.0
 * 
 */
@Path("/2.0")
public class TransactionService2DOT0 extends AbstractTransactionService {
	
	/**
	 * 巴山履历查询方法
	 */
	public static final String BASHAN_RESUME_METHOD = "bashan.resume";
	
	/**
	 * 绿色履历查询方法
	 */
	public static final String BACKWARD_RESUME_METHOD = "backward.resume";
	
	/**
	 * 配送地址列表方法
	 */
	public static final String DELIVER_ADDRESS_LIST_METHOD = "deliver.address.list";
	
	public TransactionService2DOT0() {
		init();
	}
	
	@POST
	@Path("/service")
	@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
	@BadgerFish
	public String postService2DOT0(@QueryParam("app_key") String appKey, @QueryParam("app_code") String appCode, @QueryParam("v") String version, @QueryParam("timestamp") String timestamp, @QueryParam("format") String format, @QueryParam("sign") String sign, @QueryParam("method") String method, @FormParam("data") String data){
		JSONObject result = new JSONObject();
		
		logger.info("\nappKey -> " + appKey + " appCode -> " + appCode + " version -> " + version + " timestamp -> " + timestamp + " format -> " + format + "\nmethod -> " + method + " data -> " + data + "\nsign -> " + sign);
		
		try {
			validParam2DOT0(appKey, appCode, version, timestamp, format, method, data, sign);
			
			Integer groupId = validAppParam(appKey, appCode);

			result.accumulate("invoke_result", INVOKE_SUCCESS);

			if (BASHAN_RESUME_METHOD.equals(method.toLowerCase()) || BACKWARD_RESUME_METHOD.equals(method.toLowerCase())){//八山土猪履历查询
				result.accumulate("store_data", getResumeDetails(groupId, data));
			} else if (DELIVER_ADDRESS_LIST_METHOD.equals(method.toLowerCase())) {
				
			} else {
				result.element("invoke_result", METHOD_NONEXIST);
			}
			
		} catch (ParamErrorException e1) {
			result.accumulate("invoke_result", PARAM_ERROR);
		} catch (NamingException e) {
			result.accumulate("invoke_result", INVOKE_FAILURE);
		}
		
		logger.info(result.toString());
		
		return result.toString();
	}
	
	@GET
	@Path("/service")
	@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
	@BadgerFish
	public String getService2DOT0(@QueryParam("app_key") String appKey, @QueryParam("app_code") String appCode, @QueryParam("v") String version, @QueryParam("timestamp") String timestamp, @QueryParam("format") String format, @QueryParam("sign") String sign, @QueryParam("method") String method, @QueryParam("data") String data){
		return this.postService2DOT0(appKey, appCode, version, timestamp, format, sign, method, data);
	}
	
	protected static JSONObject getResumeDetails(Integer groupId, String data) throws ParamErrorException {
		JSONObject result = new JSONObject();
		
		if (null == data){
			logger.info("Data is null");
			throw new ParamErrorException();
		}
		
		JSONObject param = JSONObject.fromObject(data);
		
		String resumeCode = param.getString("resumeCode");
		
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		
		String sql = "select lo.description, l.lockers_name, sgpn.arrival_time, sgpn.takeaway_time, sgpn.storage_grid_id from order_product_info opi inner join order_information oi on opi.order_information_id = oi.order_information_id" + 
					 " inner join lockers l on l.lockers_id = oi.lockers_id inner join location lo on l.location_id = lo.location_id inner join storage_grid_purchaser_news sgpn on oi.number = sgpn.order_information_number" +
                     " inner join product_batch pb on oi.order_information_id = pb.order_information_id where opi.resume_code = ? limit 1";
		
		try {
			conn = JDBCDataSource.getConnection();
			pstm = conn.prepareStatement(sql);
			pstm.setString(1, resumeCode);
			rs = pstm.executeQuery();
			
			Integer storageGridId = null;
			String arrivalTime = null;
			String takeawayTime = null;
			
			if (rs.next()){
				storageGridId = rs.getInt("storage_grid_id");
				arrivalTime = DateTimeHelper.dateTimeToStr(new Date(rs.getTimestamp("arrival_time").getTime()), DateTimeHelper.DEFAULT_DATE_TIME_FORMAT);
				takeawayTime = DateTimeHelper.dateTimeToStr(new Date(rs.getTimestamp("takeaway_time").getTime()), DateTimeHelper.DEFAULT_DATE_TIME_FORMAT);
				result.accumulate("delivery_address", rs.getString("description") + rs.getString("lockers_name"));
				result.accumulate("arrival_time", arrivalTime);
				result.accumulate("takeaway_time", takeawayTime);
			}
			
			if (null != storageGridId){
				rs = null;
				pstm = null;
				
				pstm = conn.prepareStatement("select temp, insert_time from storage_grid_sensor where storage_grid_id = " + storageGridId.intValue() + " and insert_time >= '" + arrivalTime + "' and insert_time <= '" + takeawayTime + "' order by insert_time asc");
				rs = pstm.executeQuery();
				
				JSONArray list = new JSONArray();
				
				while(rs.next()){
					JSONObject obj = new JSONObject();
					obj.accumulate("temp", rs.getFloat("temp"));
					obj.accumulate("gather_time", DateTimeHelper.dateTimeToStr(new Date(rs.getTimestamp("insert_time").getTime()), DateTimeHelper.DEFAULT_DATE_TIME_FORMAT));
					list.add(obj);
				}
				
				result.accumulate("temp_list", list);
			}
			
		} catch (Exception e) {
			logger.error("Query data fail!\n" + e.getMessage());
		} finally {
			JDBCDataSource.closeResource(conn, pstm, rs);
		}
		
		return result;
	}
	
	public JSONObject getDeliverAddressList(Integer groupId, String data) throws ParamErrorException {
		JSONObject result = new JSONObject();
		
		return result;
	}
}
